<template>
  <span class="comment-vote-buttons info">
    <span class="pointer m-l-16" @click="vote('like')">
      <i v-if="isLoading.like" class="el-icon-loading f-mini-plus"></i>
      <svg-icon v-else :icon-name="icon.like" class-name="f-mini-plus primary-hover-color"/>
      {{ comment.voteCount.like }}
    </span>
    <span class="pointer m-l-16" @click="vote('dislike')">
      <i v-if="isLoading.dislike" class="el-icon-loading f-mini-plus"></i>
      <svg-icon v-else :icon-name="icon.dislike" class-name="f-mini-plus primary-hover-color"/>
      {{ comment.voteCount.dislike }}
    </span>
  </span>
</template>

<script>
import * as format from './format';

export default {
  name: 'VoteIcons', // 评论区的点赞图标（按钮）
  props: {
    comment: { // 对哪个评论点赞
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      isLoading: {
        like: false,
        dislike: false,
      },
    };
  },
  computed: {
    icon() {
      return {
        like: this.comment.voteState.like ? 'like-fill' : 'like',
        dislike: this.comment.voteState.dislike ? 'dislike-fill' : 'dislike',
      };
    },
  },
  methods: {
    // 点赞、点踩
    vote(action) {
      this.isLoading[action] = true;
      const voteParams = this.initVoteParams(action);
      this.$api.other.vote(voteParams)
        .then((res) => {
          this.voteMessage(action, voteParams.voteState);
          this.$emit('update:comment', format.formatComment(res.data));
          this.$root.$emit('checkScore', this.$va.initScoreType(action, voteParams.voteState));
        })
        .catch(() => {})
        .then(() => { this.isLoading[action] = false; });
    },
    // 点赞、收藏所需参数
    initVoteParams(action) {
      return {
        votePosition: this.$C.vote.position.comment, // 对资源点赞
        votePositionId: this.comment.id, // 当前资源id
        voteAction: this.$C.vote.action[action], // 点赞、点踩
        voteState: !this.comment.voteState[action],
      };
    },
    // 点赞、收藏的提醒
    voteMessage(action, voteState) {
      if (voteState) { // 正向操作才有提醒
        if (action === 'like') this.$message.success('点赞成功');
      }
    },
  },
};
</script>

<style></style>
